# outputer.py

r'''The outputer object deals with communication with the CNC machine.

Currently only an "automatic" mode is supported, where the outputer generates
a file of instructions that the CNC machine will act upon.

In the future, there may be support for a "manual" mode, where the outputer
talks directly to the CNC machine in real-time, allowing the machine operator
to pause the run, change settings in the software, and continue the run.
'''

from __future__ import division

import sys

class file(object):
    r'''Simply outputs lines to a file.

    Will also output to sys.stdout or sys.stderr if the filename is 'stdout'
    or 'stderr', respectively.
    '''
    def __init__(self, open_mode = 'wt'):
        self.open_mode = open_mode
        self.filename = None

    def open(self, filename):
        if self.filename is not None:
            raise AssertionError("file_output.open: not closed")
        self.filename = filename
        if filename == 'stdout':
            self.f = sys.stdout
        elif filename == 'stderr':
            self.f = sys.stderr
        else:
            self.f = open(filename, self.open_mode)

    def write(self, s):
        self.f.write(s)

    def close(self):
        if self.filename is not None:
            if self.filename not in ('stdout', 'stderr'):
                self.f.close()
            self.filename = None
            del self.f

